<template>
  <div class="import">
    <el-card>
      <h2>员工导入</h2>
      <HmUpload :before-upload="beforeUpload" :on-success="onSuccess" />
    </el-card>
  </div>
</template>

<script>
import { sysUserBatch } from '@/api/employees.js'
export default {
  methods: {
    beforeUpload(file) {
      console.log(file)
      // 作用：上传前的限制，(比如限制上传的文件大小，类型等....)
      const isLimit1k = file.size / 1024 < 1024
      if (!isLimit1k) {
        this.$message.error('最多上传1024kb的文件')
      }
      return isLimit1k
    },
    async onSuccess(obj) {
      //   console.log(obj)
      /*
        correctionTime: "2022-02-09T16:00:00.000Z"
        departmentName: "技术部"
        formOfEmployment: 1
        mobile: "13777777777"
        timeOfEntry: "2022-02-06T16:00:00.000Z"
        username: "ggg"
        workNumber: "ddd"
        //--------------
        入职日期: 43535
        姓名: "高大山1"
        工号: 201893
        手机号: 13141131110
        转正日期: 43719
      */
      const rules = {
        入职日期: 'timeOfEntry',
        姓名: 'username',
        工号: 'workNumber',
        手机号: 'mobile',
        转正日期: 'correctionTime'
      }
      const arrNew = obj.results.map((item) => {
        const obj = {}
        // console.log('item', item)
        Object.keys(item).forEach((item2) => {
          //   console.log('item2', item2)
          if (item2 === '入职日期' || item2 === '转正日期') {
            obj[rules[item2]] = this.changeTime(item[item2])
          } else {
            obj[rules[item2]] = item[item2]
          }
        })
        return obj
      })
      //   console.log(arrNew)
      await sysUserBatch(arrNew)
      //   提示用户
      this.$message.success('批量新增成功')
      //   跳转到员工页面
      this.$router.push('/employees')
    },
    // 时间转换
    changeTime(num) {
      const t1 = new Date((num - 1) * 24 * 60 * 60 * 1000 - 8 * 60 * 60 * 1000)
      t1.setYear(t1.getFullYear() - 70)
      return t1
    }
  }
}
</script>

<style lang="scss" scoped>
.import {
  padding: 30px;
  h2 {
    text-align: center;
  }
}
</style>
